package com.wuwangfu.process;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author: jcshen
 * @Date: 2023-03-08
 * @PackageName: com.wuwangfu.process
 * @ClassName: ProcessFunctionTimer
 * @Description: 注册定时器OnTimer
 * @Version: 1.0.0
 * <p>
 * https://nightlies.apache.org/flink/flink-docs-release-1.14/docs/dev/datastream/operators/process_function/#timers
 */
public class ProcessFunctionOnTimer {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> lines = env.socketTextStream("localhost", 8888);
        SingleOutputStreamOperator<Tuple2<String, Integer>> maped = lines.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                String[] fields = value.split(",");
                return Tuple2.of(fields[0], Integer.parseInt(fields[1]));
            }
        });

        KeyedStream<Tuple2<String, Integer>, String> keyed = maped.keyBy(t -> t.f0);

        keyed.process(new KeyedProcessFunction<String, Tuple2<String, Integer>, Tuple2<String, Integer>>() {

            private transient ValueState<Integer> counter;

            @Override
            public void open(Configuration parameters) throws Exception {

                ValueStateDescriptor<Integer> valueDesc = new ValueStateDescriptor<>("wc-state", Integer.class);
                counter = getRuntimeContext().getState(valueDesc);
            }


            @Override
            public void processElement(Tuple2<String, Integer> value, Context ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
                //获取当前的 ProcessTime
                long timer = ctx.timerService().currentProcessingTime();
                //将当前的 ProcessTime + 1min，注册一个定时器
                //下一个分钟
                long fireTime = timer - timer % 60000 + 60000;
                //如果注册相同数据的TimeTimer，后面的会将前面的覆盖，即相同的TimeTimer只会触发一次
                ctx.timerService().registerProcessingTimeTimer(fireTime);
                /*累加*/
                Integer count = value.f1;
                Integer hiscount = counter.value();
                if (hiscount == null){
                    hiscount = 0;
                }
                Integer total = count + hiscount;
                //更新状态
                counter.update(total);
            }

            /**
             * 当闹钟到了指定时间，就执行onTimer方法
             *
             * @param timestamp
             * @param ctx
             * @param out
             * @throws Exception
             */
            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
                System.out.println("定时器执行了：" + timestamp);
                Integer value = counter.value();
                String key = ctx.getCurrentKey();
                /*如果想实现类似滚动窗口，不累加类似数据，只是累加当前窗口的数据，就清空状态*/
                //counter.update(0);
                //输出
                out.collect(Tuple2.of(key,value));
            }

        }).print();

        env.execute();
    }
}
